package com.bbbug.coree.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.bbbug.coree.entity.ReturnData;
import com.bbbug.coree.entity.Roomuserinfo;
import com.bbbug.coree.entity.Userinfo;
import com.bbbug.coree.service.RooominfoService;
import com.bbbug.coree.service.UserinfoService;
import com.bbbug.coree.utils.MiscUtil;
import com.bbbug.coree.entity.Roominfo;

import com.bbbug.coree.websocketservice.core;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.yeauty.pojo.Session;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * (Roominfo)表控制层
 *
 * @author Zixiang Gao
 * @since 2021-06-23 18:15:15
 */
@CrossOrigin(origins ="${myweb-path}" )
@RestController
@RequestMapping("api/room")
public class RoominfoController {
    @Autowired
    private RooominfoService service;
    @Autowired
    private UserinfoService userinfoService;
    @Autowired
    RedisTemplate redisTemplate;
    @RequestMapping("getRoomInfo")
    public ReturnData getRoomInfo(@RequestBody JSONObject mp) {
        Roominfo res = service.queryById(Integer.parseInt(mp.get("room_id").toString()));
        if(res==null) {
            return  new ReturnData(404,"加载失败",null);
        }
        if(res.getRoom_public().equals(1)){
            Object room_password = res.getRoom_pwd();
            Object room_password1 = mp.get("room_password");
            if(room_password==null||room_password1==null) {
                return new ReturnData(302,"null",null);
            } else if(!(room_password1.equals(room_password))){
                return new ReturnData(302,"错误密码",null);
            }
        }
        res.setRoom_online(core.CHATMAP.get("room_id")==null?0:core.CHATMAP.get(mp.get("room_id")).size());
        Userinfo admin = userinfoService.queryById(Integer.parseInt(res.getAdmin().toString()));
        Map<String, Object> tp = BeanUtil.beanToMap(res);
        tp.put("admin",admin);
        if(res.getRoom_votepass()!=null&&res.getRoom_votepass()!=-1){
            tp.put("room_votepass","打开投票切歌");
            tp.put("room_votepercent",res.getRoom_votepass());
        }else{
            tp.put("room_votepass","关闭投票切歌");
        }
        return new ReturnData(200,"加载成功",tp);
    }
    @CrossOrigin(origins = "*")
    @RequestMapping("getWebsocketUrl")
    public void getWebsocketUrl(@RequestBody JSONObject map, HttpServletRequest request, HttpServletResponse response){
        JSONObject map1=new JSONObject();
        String access_token = (String) map.get("access_token");
        String s = MiscUtil.verifyToken(access_token);
        JSONObject login=new JSONObject();
        try {
            if (!request.getRemoteAddr().equals("127.0.0.1")) {
                URL url = new URL("http://www.36ip.cn/?ip=" + request.getRemoteAddr());
                BufferedReader r = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream(),"UTF-8"));
                login.put("where", r.readLine().split(" ")[0]);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        login.put("type","join");
        if(s==null&&(map.getString("plat")==null||map.getString("plat").equals("vue"))){
            map1.put("account",request.getRemoteAddr());
            login.put("content","欢迎临时用户加入本房间");
            login.put("user",null);
            login.put("name","临时用户");
        }else if(map.getString("plat").equals("player")){
            map1.put("account",request.getRemoteAddr());
            login.put("content","有个外链播放器用户来了 但他看不到 我们不告诉ta");//其实这句话是没用的 只能能f12里network里看到
            login.put("user",null);
            login.put("name","外链播放器用户");
        }else{
            Userinfo userinfo = userinfoService.queryById(Integer.parseInt(s));
            if(core.CHATMAP.get(map.get("channel").toString())==null||core.CHATMAP.get(map.get("channel").toString()).get(s)==null) {
                map1.put("account",s);
            } else {
                map1.put("account",s+RandomUtil.randomString(5));
            }
            login.put("content","欢迎用户"+userinfo.getUser_name()+"回家");
            login.put("name",userinfo.getUser_name());
            login.put("user",userinfo);
        }
        map1.put("channel",map.get("channel"));
        map1.put("ticket",MiscUtil.createToken(map.get("channel").toString()));
        try {
            PrintWriter writer = response.getWriter();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code",200);
            jsonObject.put("msg","success");
            jsonObject.put("data",map1);
            writer.write(jsonObject.toJSONString());
            writer.close();
            Thread.sleep(500);
            SendForALL(map.get("channel").toString(),login.toJSONString());
        } catch (Exception e) {
           //do nothing
        }

//        List<Userinfo> userinfos=new Vector<>();
//        ConcurrentHashMap<String, Session> channel = core.CHATMAP.get(map.get("channel").toString());
//        for(String x:channel.keySet()){
//            if(!x.contains(":"))
//            userinfos.add(userinfoService.queryById(Integer.parseInt(x)));
//        }
//        JSONObject jsonObject=new JSONObject();
//        jsonObject.put("type","online");
//        jsonObject.put("channel",map.get("channel"));
//        jsonObject.put("data",userinfos);
//        SendForALL(map.get("channel").toString(),jsonObject.toJSONString());
        //return new ReturnData(200,"success",map1);
    }
    @RequestMapping("create")
    ReturnData returnData(@RequestBody Map mp){
        String access_token = mp.get("access_token").toString();
        Object name=mp.get("room_name");
        Object room_notice=mp.get("room_notice");
        String s = MiscUtil.verifyToken(access_token);
        Object room_type = mp.get("room_type");
        System.out.println(s);
        if(s==null){

            return new ReturnData(403,"创建失败 请登陆",null);
        }else if(service.queryByadmin(Integer.parseInt(s)).size()!=0){
            return new ReturnData(200,"你已经有一个房间了，你是怎么发送的这个请求？",null);
        }
        int i = RandomUtil.randomInt(10000, 99999);
        while(service.queryById(i)!=null){
            i=RandomUtil.randomInt(10000, 99999);
        }
       // SongTask.needsbbot.put(i+"",new Integer[]{0});
        /*int update = jdbcTemplate.update("insert into roominfo (room_id,room_user,room_name, room_type, room_order, room_status, room_public, admin) value (?,?,?,?,?,?,?,?)",i ,s, name, room_type, room_notice, 0, 0, s);
        */
        Roominfo roominfo = new Roominfo();
        roominfo.setRoom_id(i);
        roominfo.setRoom_user(Integer.parseInt(s));
        roominfo.setRoom_name(name.toString());
        roominfo.setRoom_type(Integer.parseInt(room_type.toString()));
        roominfo.setRoom_notice(room_notice.toString());
        roominfo.setRoom_status(0);
        roominfo.setRoom_public(0);
        roominfo.setAdmin(Integer.valueOf(s));
        Roominfo update=service.insert(roominfo);
        if(update!=null){
            return new ReturnData(200,"成功",service.queryById(i));
        }
        return new ReturnData(500,"失败","");
    }
    @RequestMapping("hotRooms")
    ReturnData getHotRooms(){
        List<Roomuserinfo> maps = service.queryAll();
        int len=maps.size();
        for(int i=0;i<len;i++){
            maps.get(i).setRoom_online(core.CHATMAP.get(maps.get(i).getRoom_id().toString())==null?0:core.CHATMAP.get(maps.get(i).getRoom_id().toString()).size());
        }
        return new ReturnData(200,"",maps);
    }
    @RequestMapping("saveMyRoom")
    ReturnData saveMyRoom(@RequestBody JSONObject mp){
        String user_id=MiscUtil.verifyToken(mp.get("access_token").toString());
        Object room_public=mp.get("room_public");
        Object room_pwd=mp.get("room_password");
        Object room_name = mp.get("room_name");
        Object room_order = mp.get("room_notice");
        Object room_status = mp.get("room_hide");
        Integer room_robot = (Integer)mp.get("room_robot");
        Object room_id = mp.get("room_id");
        Integer room_sendmsg = mp.getInteger("room_sendmsg");

        List<Roominfo> thisadmin=service.queryByadmin(Integer.parseInt(user_id));
        if(user_id==null||thisadmin.size()==0||!thisadmin.get(0).getRoom_id().equals((Integer)room_id)){
            return new ReturnData(403,"无权修改",null);
        }else{
            Roominfo roominfo = new Roominfo();
            roominfo.setRoom_background((mp.get("room_background")==null?"":mp.get("room_background")).toString());
            roominfo.setRoom_public(Integer.parseInt(room_public.toString()));
            if(room_name==null) {
                return new ReturnData(200,"请输入房间名字",null);
            }
            roominfo.setRoom_name(room_name.toString());
            roominfo.setRoom_status((room_status==null?0:1));
            roominfo.setRoom_notice((room_order==null?"":room_order).toString());
            roominfo.setRoom_pwd((room_pwd==null?"":room_pwd).toString());
            roominfo.setRoom_id(Integer.parseInt(room_id.toString()));
            roominfo.setRoom_robot(room_robot);
            roominfo.setRoom_sendmsg(room_sendmsg);
            Integer room_type= mp.getInteger("room_type");
            roominfo.setRoom_type(room_type);
            roominfo.setRoom_addsong(mp.getInteger("room_addsong")==null?0:mp.getInteger("room_addsong"));
            roominfo.setRoom_addsongcd(mp.get("room_addsongcd")==null?-1:Integer.parseInt(mp.get("room_addsongcd").toString()));
            roominfo.setRoom_pushsongcd(mp.get("room_pushsongcd")==null?-1:Integer.parseInt(mp.get("room_pushsongcd").toString()));
            roominfo.setRoom_addcount(mp.get("room_addcount")==null?-1:Integer.parseInt(mp.get("room_addcount").toString()));
            roominfo.setRoom_votepass(mp.get("room_votepercent")==null?-1:Integer.parseInt(mp.get("room_votepercent").toString()));
            roominfo.setRoom_playone(mp.getInteger("room_playone")==null?0:mp.getInteger("room_playone"));
            roominfo.setRoom_pushdaycount(mp.getInteger("room_pushdaycount")==null?0:mp.getInteger("room_pushdaycount"));
            if(mp.getInteger("room_type")==0){
                redisTemplate.delete(room_id.toString());
            }
            service.update(roominfo);
            return new ReturnData(200,"修好了",null);
        }
    }

    boolean SendForALL(String room_id,String message) {

        ConcurrentHashMap<String, Session> stringSessionConcurrentHashMap = core.CHATMAP.get(room_id);
            if (stringSessionConcurrentHashMap == null) {
                return false;
            }
            for (Session value : stringSessionConcurrentHashMap.values()) {
                value.sendText(message);
            }
            return true;

    }

}